//jiaru.js
const nt_util = require('../../utils/nt_util.js')
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
let app = getApp();

// 实例化腾讯地图API核心类
var qqmapsdk = new QQMapWX({
  key: app.globalData.QQMapWXKey // 必填
});

Page({
  data: {
    storeIndex:0,
    typeId:'',
    storeTypeList: [],
    storeTypeListOrigin: [],
    dptp: '',
    yyzz: '',
    dptp_url: '',
    yyzz_url: '',
    name: '',
    storeName:'',
    address:'',
    addressInfo:'',
    phone: '',
    phoneBak:'',
    location: { lat:'',lng:''},
    map_width:'',
    map_height:'',
    controls: [],
    btn_saveStoreInfo:false
  },

  onLoad: function () {
    var that = this
   
    //1、获取当前位置坐标
    wx.getLocation({
      type: 'gcj02',// 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success: function (res) {
        //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (addressRes) {
            var address = addressRes.result.formatted_addresses.recommend;
            that.setData({
              location: { lat: res.latitude, lng:res.longitude},
              address:address
            })
          }
        })
      }
    }),

    // 动态设置map的宽和高
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          map_width: res.windowWidth - 12*2*2, 
          map_height: res.windowWidth / 2 - 10, 
          controls: [{
            id: 1,
            iconPath: '/imgs/ic_position.png',
            position: {
              left: res.windowWidth / 2 - 10 - 8 - 15,
              top: res.windowWidth / 4 - 15,
              width: 30,
              height: 30
            },
            clickable: false
          }]
        })
      }
    }),

    that.getStoreTypeList();

  },

  //获取中间点的经纬度，并mark出来
  getLngLat: function () {
    var that = this;
    this.mapCtx = wx.createMapContext("address_map");
    this.mapCtx.getCenterLocation({
      success: function (res) {
        that.setData({
          location: { lat: res.latitude, lng: res.longitude }
        })
        //根据坐标获取当前位置名称，显示腾讯地图逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (addressRes) {
            if (addressRes){
              var address = addressRes.result.formatted_addresses.recommend;
              that.setData({
                address: address
              })
            }
          }
        })
      }
    })
  },

  regionchange:function(e){
    // 地图发生变化的时候，获取中间点，也就是用户选择的位置
    if (e.type == 'end') {
      this.getLngLat()
    }
  },
  
  chooseImage: function (e) {
    var that = this;
    nt_util.chooseImage(function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      var dataset = e.currentTarget.dataset;
      if (dataset.type == "1") {
        that.setData({
          yyzz: res[0]
        });
      } else {
        that.setData({
          dptp: res[0]
        });
      }
    }, function (res) {

    });
  },

  previewImage: function (e) {
    nt_util.previewImage(e.currentTarget.id, [e.currentTarget.id]);
  },

  // 获取店铺类型列表
  getStoreTypeList:function(){
    var that = this;
    nt_util.httpRequest('api/life/v1/getStoreTypeList', 'post', {}, function (res) {
      var _list = res.data.list || [];
      var _storeTypeList = [];
      for (var i = 0; i < _list.length; i++){
        _storeTypeList.push(_list[i].name);
        // that.data.storeTypeList.push(_list[i].name);//这样不会绑定数据, setData 会双向绑定数据
      }
      that.setData({
        storeTypeList: _storeTypeList,
        storeTypeListOrigin: _list,
        typeId: _list[0].id
      });
    });
  },

// 保存门店信息
  saveStoreInfo: function(e){
    var that = this;
    
    if (that.data.btn_saveStoreInfo){
      wx.showModal({
        title: '提示',
        content: '您已提交，等待后台审核！',
        showCancel:false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    }
    that.setData({
      btn_saveStoreInfo: true,
    });


    if(!that.checkParams()){
      return false;
    }

    nt_util.uploadFile('api/life/v1/uploadImage', that.data.dptp, '', { type:'store'}, function (res) {
      that.setData({
        dptp_url: res.data.imageUrl
      })
      nt_util.uploadFile('api/life/v1/uploadImage', that.data.yyzz, '', { type: 'scopePic' }, function (res2) {
        that.setData({
          yyzz_url: res2.data.imageUrl
        })

        var params = {
          address: that.data.address + that.data.addressInfo,
          name: that.data.name,
          lat: that.data.location.lat,
          lng: that.data.location.lng,
          phone: that.data.phone,
          storeName: that.data.storeName,
          phoneBak: that.data.phoneBak,
          scopePic: that.data.yyzz_url,
          storePic: that.data.dptp_url,
          typeId: that.data.typeId,
        };
        nt_util.httpRequest('api/life/v1/saveStoreInfo', 'post', params, function (res) {
          that.setData({
            dptp: '',
            yyzz: '',
            name: '',
            storeName: '',
            phone: '',
            phoneBak: '',
            addressInfo: ''
          })

          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1500,
            complete:function(res){
              setTimeout(function(){
                wx.setStorage({
                  key: "home_reload",
                  data: "true"
                })
                wx.switchTab({
                  url: '/pages/index/index'
                })
              },1500);
            }
          })
          
        });
      }, function (fail) {

      });
    }, function (fail) {

    });
    
  },

  checkParams:function (){
    var that = this;
    
    if (!that.data.dptp) {
      wx.showToast({
        title: '店铺图片不能为空',
      })
      return false;
    }
    if (!that.data.yyzz) {
      wx.showToast({
        title: '营业执照不能为空',
      })
      return false;
    }
    if (!that.data.name) {
      wx.showToast({
        title: '商户姓名不能为空',
      })
      return false;
    }
    if (!that.data.address) {
      wx.showToast({
        title: '商户地址不能为空',
      })
      return false;
    }
    if (!that.data.storeName) {
      wx.showToast({
        title: '商店名称不能为空',
      })
      return false;
    }
    if (!that.data.phone) {
      wx.showToast({
        title: '号码不能为空',
      })
      return false;
    }
    if (!that.data.phoneBak) {
      wx.showToast({
        title: '备用号码不能为空',
      })
      return false;
    }
    return true;
  },

  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    var _storeIndex = e.detail.value;
    var _typeId = this.data.storeTypeListOrigin[_storeIndex].id;
    this.setData({
      storeIndex: _storeIndex,
      typeId: _typeId
    })
  },

  bindKeyInput:function(e){
    var that = this;
    var dataset = e.currentTarget.dataset;
    var data_type = e.detail.value;
    switch (dataset.type){
      case 'name':
        that.setData({
          name: data_type
        });
        break;
      case 'storeName':
        that.setData({
          storeName: data_type
        });
        break;
      case 'phone':
        that.setData({
          phone: data_type
        });
        break;
      case 'phoneBak':
        that.setData({
          phoneBak: data_type
        });
        break;
      case 'addressInfo':
        that.setData({
          addressInfo: data_type
        });
        break;
    }
  }


})
